package com.xms.security.service.dataauth;

import com.xms.dependency.XmsDependencyException;
import com.xms.schema.entity.Entity;
import com.xms.schema.event.EntityMetaDeletedEvent;
import com.xms.utils.CollectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.sql.SQLException;

/**
 * <p>
 * 实体删除后，级联删除权限项
 * </p>
 *
 * @author migo
 * @since 2021/10/27
 */
@Service
public class EntityPermissionCascadeDeleter {
    private IEntityPermissionDeleterService _entityPermissionDeleterService;

    @Autowired
    public void EntityPermissionCascadeDeleter(IEntityPermissionDeleterService entityPermissionDeleterService) {
        _entityPermissionDeleterService = entityPermissionDeleterService;
    }

    public boolean cascadeDelete(Entity... parent) throws SQLException {
        if (CollectionUtil.isEmpty(parent)) {
            return false;
        }
        for (Entity e : parent) {
            _entityPermissionDeleterService.deleteByEntityId(e.getEntityid());
        }
        return true;
    }

    @Async
    @EventListener()
    public void onApplicationEvent(EntityMetaDeletedEvent event) throws XmsDependencyException, SQLException {
        this.cascadeDelete(event.source);
    }
}
